<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_chenyang_make_photo')){
    class Api_chenyang_make_photo extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Chenyangmakephotocustomermodel','m_customer');
            $this->load->model('Chenyangmakephotolotterytimemodel','m_lottery_time');
            $this->load->model('configmodel','m_config');
            $this->load->database();


            $game_deadline = $this->m_config->getConfig(CHENYANG_MAKE_PHOTO_GAME_DEADLINE);
            if(!empty($game_deadline) && strtotime($game_deadline) < time()) {
                $this->response->setDetail('活动已结束!');
                $this->response->responseExit();
            }

            // $this->_action = $this->uri->rsegments[1].'/'.$this->uri->rsegments[2];
            // if($this->session->userdata($this->_action) !== false) {
            //     $this->response->setDetail('请求太快，请稍后再试!');
            //     $this->response->responseExit();
            // }
            // $this->session->set_userdata($this->_action,true);
            // //api开头的不存
            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
                return;
            }
            $info = $this->input->post();
            if(isset($info['img_base64'])) {
                unset($info['img_base64']);
            }
            $this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                // 'customer_id' => $this->m_app->getCurrentCustomerId(),
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info),
                'result_data' => '',
                'api_log_time_create' => NOW,
                // 'terminal' => TERMINAL_WEIXIN,
            ));
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            $this->db->close();
        }


        public function initCustomer() {
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('openid_md5','string');
            $this->validate->setRule('openid_md5','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('province','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('city','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('country','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('headimgurl','message',$this->lang->line('error_parameter'));
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            unset($info['openid_md5']);


            
            $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
            if(empty($customer)) {
                $info['customer_time_create'] = NOW;
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('初始化用户失败！请刷新页面！');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else if($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl']){
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer = $this->m_customer->getCustomer($info['customer_id']);
            }
            $customer['nickname'] = urldecode($customer['nickname']);

            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }
            $this->session->set_userdata('chenyang_make_photo_customer',$customer);


            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
                'lottery_avaliable' => $this->m_customer->checkIsHasLotteryChance($customer['customer_id']),
            ));
            $this->response->responseExit();
        }

        public function submitPhoto() {
            $customer = $this->session->userdata('chenyang_make_photo_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $this->validate->setRule('img_base64','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            //保存base64字符串为图片
            //匹配出图片的格式
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $info['img_base64'], $result)){
              $type = $result[2];
              if($type == 'jpeg') {
                $type = 'jpg';
              }
              $this->m_app->initFolder();
              $filename = 'chenyang_'.date('YmdHis').$customer['customer_id'].".{$type}";
              $path = UPLOAD_PATH_ORIGIN.$filename;
              if (file_put_contents($path, base64_decode(str_replace($result[1], '', $info['img_base64'])))){
                    $info['img_base64'] = $filename;
              } else {
                $this->response->setDetail('图片保存失败!请重新上传!');
                $this->response->responseExit();
              }
            } else {
                $this->response->setDetail('图片格式上传错误!请重新上传!');
                $this->response->responseExit();
            }

            $this->m_customer->createPhoto(array(
                'customer_id' => $customer['customer_id'],
                'photo_path' => $filename,
                'photo_time_create' => NOW,
            ));


            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'img_url' => UPLOAD_URL_ORIGIN.$filename,
            ));
            $this->response->responseExit();
        }

        public function drawnLottery() {
            $customer = $this->session->userdata('chenyang_make_photo_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }
            if($this->m_customer->checkIsHasLotteryChance($customer['customer_id']) == false) {
                $this->response->setDetail('今天的抽奖机会已用完，明天再来吧!');
                $this->response->responseExit();
            }

            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            // $time = time();
            // $last_time = $this->m_customer->getLastLotteryTime($customer['customer_id']);
            // if($time - $last_time < 15) {
            //     $this->m_customer->editCustomer(array(
            //         'customer_id' => $customer['customer_id'],
            //         'customer_status' => -2,
            //     ));
            //     $customer = $this->m_customer->getCustomer($customer['customer_id']);
            //     $customer['nickname'] = urldecode($customer['nickname']);
            //     $this->session->set_userdata('chenyang_make_photo_customer',$customer);
            //     $this->response->setDetail('您存在恶意刷屏!');
            //     $this->response->responseExit();
            // }
            
            $customer = $this->m_customer->getCustomerByOpenid($customer['openid']);

            $lottery_result = 0;

            $lottery_time_id=0;

            $baseNum = 1000000000;
            $money = 0;
            $gift_code = array();

            $lotteryTime = $this->m_lottery_time->getCurrentLotteryTimeRate();
            if(!empty($lotteryTime)) {
                $lottery_time_id = $lotteryTime['lottery_time_id'];
                $lottery_time_gift1_rate = floatval($lotteryTime['lottery_time_gift1_rate']);
                $lottery_time_gift2_rate = floatval($lotteryTime['lottery_time_gift2_rate']);
                $lottery_time_gift3_rate = floatval($lotteryTime['lottery_time_gift3_rate']);
                $lottery_time_gift4_rate = floatval($lotteryTime['lottery_time_gift4_rate']);
                $lottery_time_gift5_rate = floatval($lotteryTime['lottery_time_gift5_rate']);
                $lottery_time_gift6_rate = floatval($lotteryTime['lottery_time_gift6_rate']);
                $lottery_time_gift7_rate = floatval($lotteryTime['lottery_time_gift7_rate']);

                $num = rand(1,$baseNum);
                $gift_rate = 0;

                $gift_rate += $lottery_time_gift1_rate;
                if((stripos($customer['gift_type_ids'], '[1,') === false 
                    && stripos($customer['gift_type_ids'], '[2,') === false) 
                    && $lottery_result == 0 && $lottery_time_gift1_rate > 0 && $num <= $gift_rate*$baseNum
                    && intval($lotteryTime['lottery_time_gift1_count']) > intval($lotteryTime['lottery_time_gift1_count_drawn'])) {
                    $lottery_result = 1;
                }
                $gift_rate += $lottery_time_gift2_rate;
                if((stripos($customer['gift_type_ids'], '[1,') === false 
                    && stripos($customer['gift_type_ids'], '[2,') === false) 
                    && $lottery_result == 0 && $lottery_time_gift2_rate > 0 && $num <= $gift_rate*$baseNum
                    && intval($lotteryTime['lottery_time_gift2_count']) > intval($lotteryTime['lottery_time_gift2_count_drawn'])) {
                    $lottery_result = 2;
                }
                $gift_rate += $lottery_time_gift3_rate;
                if($lottery_result == 0 && $lottery_time_gift3_rate > 0 && $num <= $gift_rate*$baseNum
                    && intval($lotteryTime['lottery_time_gift3_count']) > intval($lotteryTime['lottery_time_gift3_count_drawn'])) {
                    $lottery_result = 3;
                    $money = 180;
                }
                $gift_rate += $lottery_time_gift4_rate;
                if($lottery_result == 0 && $lottery_time_gift4_rate > 0 && $num <= $gift_rate*$baseNum
                    && intval($lotteryTime['lottery_time_gift4_count']) > intval($lotteryTime['lottery_time_gift4_count_drawn'])) {
                    $lottery_result = 4;
                    $money = 18;
                }
                $gift_rate += $lottery_time_gift5_rate;
                if($lottery_result == 0 && $lottery_time_gift5_rate > 0 && $num <= $gift_rate*$baseNum
                    && intval($lotteryTime['lottery_time_gift5_count']) > intval($lotteryTime['lottery_time_gift5_count_drawn'])) {
                    $lottery_result = 5;
                    $money = 1.8;
                }
                $gift_rate += $lottery_time_gift6_rate;
                if($lottery_result == 0 && $lottery_time_gift6_rate > 0 && $num <= $gift_rate*$baseNum
                    && intval($lotteryTime['lottery_time_gift6_count']) > intval($lotteryTime['lottery_time_gift6_count_drawn'])) {
                    $lottery_result = 6;
                    $money = 1;
                }
                $gift_rate += $lottery_time_gift7_rate;
                //如果未中奖，中优惠券
                if($lottery_result == 0) {
                    $gift_code = $this->m_customer->getAvailableGiftCode();
                    if(!empty($gift_code)) {
                        $lottery_result = 7;
                        $this->m_customer->editGiftCode(array(
                            'gift_code_id' => $gift_code['gift_code_id'],
                            'gift_code_status' => STATUS_ACTIVE,
                            'gift_code_time_use' => NOW,
                        ));
                    }
                }
                // if($lottery_result == 0 && $lottery_time_gift7_rate > 0 && ($customer['lottery_times'] == 2 || $num <= $gift_rate*$baseNum)
                //     && intval($lotteryTime['lottery_time_gift7_count']) > intval($lotteryTime['lottery_time_gift7_count_drawn'])) {
                //     $gift_code = $this->m_customer->getAvailableGiftCode();
                //     if(!empty($gift_code)) {
                //         $lottery_result = 7;
                //         $this->m_customer->editGiftCode(array(
                //             'gift_code_id' => $gift_code['gift_code_id'],
                //             'gift_code_status' => STATUS_ACTIVE,
                //             'gift_code_time_use' => NOW,
                //         ));
                //     }
                // }
            }

            $money_status = STATUS_PENDING;
            $money_result = '';
            if(ONLINE && $money > 0) {
                $money_result = $this->_wxhongbao($customer['openid'],$money*100);
                if($money_result->result_code=='SUCCESS'){
                    $money_status = STATUS_ACTIVE;
                }else{
                    $money_status = STATUS_DISABLE;
                    $lottery_result = 0; //红包失败，则未抽奖成功
                    $money = 0;
                }
            }
            $money_result = json_encode($money_result, JSON_UNESCAPED_UNICODE);

            //记录数据库
            $this->m_customer->createLotteryHistory(array(
                'customer_id' => $customer['customer_id'],
                'lottery_time_id' => empty($lotteryTime) ? 0 : $lotteryTime['lottery_time_id'],
                'gift_type' => $lottery_result,
                'gift_code_id' => empty($gift_code) ? 0 : $gift_code['gift_code_id'],
                'money' => $money,
                'money_result' => $money_result,
                'money_status' => $money_status,
                'lottery_time_time_create' => NOW,
            ));


            $this->m_customer->updateCustomerLotteryCount($customer['customer_id']);

            if($lottery_result > 0) {
                $gift_type_ids = json_decode($customer['gift_type_ids']);
                $gift_type_ids[] = [intval($lottery_result),$money,empty($gift_code) ? 0 : $gift_code['gift_code_id']];
                $this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'lottery_time_id' => empty($lotteryTime) ? 0 : $lotteryTime['lottery_time_id'],
                    'gift_type' => $lottery_result,
                    'gift_type_ids' => json_encode($gift_type_ids),
                    'gift_code_id' => empty($gift_code) ? 0 : $gift_code['gift_code_id'],
                    'customer_time_lottery' => NOW,
                ));
                $this->m_lottery_time->updateLotteryCountDrawn($lottery_time_id,$lottery_result);
            }

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $customer['nickname'] = urldecode($customer['nickname']);
            $this->session->set_userdata('chenyang_make_photo_customer',$customer);
            
            global $g_chenyang_make_photo_gift;
            $addon = array();
            $addon['gift_type'] = $lottery_result;
            $addon['gift_code'] = empty($gift_code) ? '' : $gift_code['gift_code'];
            $addon['money'] = $money;
            $addon['gift_name'] = id2name($lottery_result,$g_chenyang_make_photo_gift);

            $this->response->setSuccess();
            $this->response->setAddon($addon);
            $this->response->responseExit();
        }

        public function submitAddress() {
            $customer = $this->session->userdata('chenyang_make_photo_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            if($customer['gift_type'] == 0) {
                $this->response->setDetail('您还未中奖!');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_name','string');
            $this->validate->setRule('customer_name','message','请填您的姓名');
            $this->validate->setRule('customer_phone','string');
            $this->validate->setRule('customer_phone','message','请填您的手机号');
            $this->validate->setRule('customer_address','string');
            $this->validate->setRule('customer_address','message','请填您的收货地址');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }

            
            $info['customer_id'] = $customer['customer_id'];
            $this->m_customer->editCustomer($info);

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $this->session->set_userdata('chenyang_make_photo_customer',$customer);
            
            $this->response->setSuccess();
            $this->response->setDetail('收货地址提交成功!');
            $this->response->responseExit();
        }

        public function dbview() {
            $data['desc'] = '清除晨阳水漆数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }
        public function clearDb(){
            $this->db->truncate('chenyang_make_photo_customer'); 
            $this->db->truncate('chenyang_make_photo_lottery_history'); 
            
            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }


        private function _wxhongbao($openid = '', $db = 0) {
            if(empty($openid) || $db <= 0 || $db > 20000) {
                return '参数错误-openid('.$openid.'),$db('.$db.')';
            }

            @require dirname(BASEPATH)."/application/third_party/wxHongBao/pay.php";
            $packet = new Packet();

            $result = $packet->_route('wxpacket',array('openid'=>$openid),$db,md5($db.FREEDOM_WAR_SALT));

            return $result;
        }
    }
    
}